import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_base/config/app_color.dart';

/// 日期选择器组件
/// 用于在底部弹窗中选择日期（年、月、日三联动）
class DatePickerWidget extends StatefulWidget {
  /// 初始日期
  final DateTime? initialDate;

  /// 日期选择回调
  final Function(DateTime date)? onDateSelected;

  /// 最小日期
  final DateTime? firstDate;

  /// 最大日期
  final DateTime? lastDate;

  const DatePickerWidget({
    Key? key,
    this.initialDate,
    this.onDateSelected,
    this.firstDate,
    this.lastDate,
  }) : super(key: key);

  @override
  State<DatePickerWidget> createState() => _DatePickerWidgetState();
}

class _DatePickerWidgetState extends State<DatePickerWidget> {
  late DateTime _selectedDate;
  late int _selectedYear;
  late int _selectedMonth;
  late int _selectedDay;

  // 年份范围（默认1900-当前年份）
  late List<int> _years;

  // 月份范围（1-12）
  final List<int> _months = List.generate(12, (index) => index + 1);

  // 日期范围（根据年月动态计算）
  late List<int> _days;

  @override
  void initState() {
    super.initState();

    // 初始化日期
    _selectedDate = widget.initialDate ?? DateTime.now();
    _selectedYear = _selectedDate.year;
    _selectedMonth = _selectedDate.month;
    _selectedDay = _selectedDate.day;

    // 初始化年份范围
    final firstYear = widget.firstDate?.year ?? 1900;
    final lastYear = widget.lastDate?.year ?? DateTime.now().year;
    _years =
        List.generate(lastYear - firstYear + 1, (index) => firstYear + index);

    // 初始化日期范围
    _updateDays();
  }

  // 更新日期范围
  void _updateDays() {
    final daysInMonth = DateTime(_selectedYear, _selectedMonth + 1, 0).day;
    _days = List.generate(daysInMonth, (index) => index + 1);

    // 确保选中的日期不超过当月的最大天数
    if (_selectedDay > daysInMonth) {
      _selectedDay = daysInMonth;
    }
  }

  // 更新选择的日期
  void _updateSelectedDate() {
    _selectedDate = DateTime(_selectedYear, _selectedMonth, _selectedDay);
    if (widget.onDateSelected != null) {
      widget.onDateSelected!(_selectedDate);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          decoration: BoxDecoration(
            color: AppColor.colorF5F5F5,
            borderRadius: BorderRadius.circular(20.w),
          ),
          child: Column(
            children: [
              // 分类标签
              SizedBox(
                height: 38.w,
                child: Row(
                  children: [
                    _buildHeaderItem('Year'),
                    _buildHeaderItem('Month'),
                    _buildHeaderItem('Day'),
                  ],
                ),
              ),

              // 滚动选择器
              SizedBox(
                height: 185.w,
                child: Row(
                  children: [
                    // 年份选择器
                    Expanded(
                      child: CupertinoPicker(
                        selectionOverlay: _buildSelectionOverlay(),
                        backgroundColor: Colors.transparent,
                        itemExtent: 40.w,
                        scrollController: FixedExtentScrollController(
                          initialItem: _years.indexOf(_selectedYear),
                        ),
                        onSelectedItemChanged: (index) {
                          setState(() {
                            _selectedYear = _years[index];
                            _updateDays();
                            _updateSelectedDate();
                          });
                        },
                        children: _years
                            .map((year) => _buildPickerItem(year.toString()))
                            .toList(),
                      ),
                    ),

                    // 月份选择器
                    Expanded(
                      child: CupertinoPicker(
                        selectionOverlay: _buildSelectionOverlay(),
                        backgroundColor: Colors.transparent,
                        itemExtent: 40.w,
                        scrollController: FixedExtentScrollController(
                          initialItem: _selectedMonth - 1,
                        ),
                        onSelectedItemChanged: (index) {
                          setState(() {
                            _selectedMonth = _months[index];
                            _updateDays();
                            _updateSelectedDate();
                          });
                        },
                        children: _months
                            .map((month) => _buildPickerItem(
                                  month.toString().padLeft(2, '0'),
                                ))
                            .toList(),
                      ),
                    ),

                    // 日期选择器
                    Expanded(
                      child: CupertinoPicker(
                        selectionOverlay: _buildSelectionOverlay(),
                        backgroundColor: Colors.transparent,
                        itemExtent: 40.w,
                        scrollController: FixedExtentScrollController(
                          initialItem: _days.indexOf(_selectedDay) >= 0
                              ? _days.indexOf(_selectedDay)
                              : 0,
                        ),
                        onSelectedItemChanged: (index) {
                          setState(() {
                            _selectedDay = _days[index];
                            _updateSelectedDate();
                          });
                        },
                        children: _days
                            .map((day) => _buildPickerItem(
                                  day.toString().padLeft(2, '0'),
                                ))
                            .toList(),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 创建选择器的高亮覆盖层
  Widget _buildSelectionOverlay() {
    return Container(
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(
            color: AppColor.colorF5F5F5.withOpacity(0.3),
            width: 1.w,
          ),
          bottom: BorderSide(
            color: AppColor.colorF5F5F5.withOpacity(0.3),
            width: 1.w,
          ),
        ),
      ),
    );
  }

  // 构建头部标签项
  Widget _buildHeaderItem(String title) {
    return Expanded(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 10.w),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            fontFamily: 'Outfit',
            color: AppColor.color0C0A09,
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  // 构建选择器项
  Widget _buildPickerItem(String text) {
    return Center(
      child: Text(
        text,
        style: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.w600,
          fontFamily: 'Outfit',
          color:
              _isSelectedItem(text) ? AppColor.primary : AppColor.color0C0A09,
        ),
      ),
    );
  }

  // 判断是否为选中项
  bool _isSelectedItem(String text) {
    return text == _selectedYear.toString() ||
        text == _selectedMonth.toString().padLeft(2, '0') ||
        text == _selectedDay.toString().padLeft(2, '0');
  }
}
